package com.polonium.pageobject.spring;

import com.polonium.pageobject.selenium.WaitWebDriverEventListener;
import com.polonium.pageobject.selenium.WebDriverType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.springframework.beans.factory.FactoryBean;

public class WebDriverFactoryBean implements FactoryBean<WebDriver> {

	public static final WebDriverType DEFAULT_TYPE = WebDriverType.HTMLUNIT;
	private WebDriverType type = getType();

	private WebDriverType getType() {

		String typeName = System.getProperty("polonium.webdriver.type");

		try {
			return WebDriverType.valueOf(typeName);
		} catch (Exception e) {
			return DEFAULT_TYPE;
		}
	}

	private EventFiringWebDriver webDriver;

	@Override
	public WebDriver getObject() throws Exception {
		if (webDriver == null) {
			switch (type) {
				case FIREFOX:
					webDriver = new EventFiringWebDriver(new FirefoxDriver());
					break;
				case CHROME:
					webDriver = new EventFiringWebDriver(new ChromeDriver());
					break;
				case HTMLUNIT:
					HtmlUnitDriver htmlUnitDriver = new HtmlUnitDriver();
					htmlUnitDriver.setJavascriptEnabled(true);
					webDriver = new EventFiringWebDriver(htmlUnitDriver);
					break;
				case IE:
//					File file = new File("C:/IEDriver.exe");
//					System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
					webDriver = new EventFiringWebDriver(new InternetExplorerDriver());
					break;
				default:
					throw new RuntimeException("Unknown web driver type: " + type.name());
			}

			webDriver.register(new WaitWebDriverEventListener());
		}

		return webDriver;
	}

	@Override
	public Class<?> getObjectType() {
		return EventFiringWebDriver.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

}
